package com.hao.epidemic_prevention.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hao.epidemic_prevention.utils.JSONResult;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @SneakyThrows
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //response.setStatus(401);

        PrintWriter out = httpServletResponse.getWriter();
        JSONResult result = new JSONResult(401, "未登录！", null);

        out.write(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();

        logger.error("未登录，无法访问！");
        //throw new NotLoggedInException();
    }
}
